package com.github.sys.shiro.demo.realm;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.github.sys.shiro.demo.entity.User;
import com.github.sys.shiro.demo.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * <p>User: 
 * <p>Date: 14-2-13
 * <p>Version: 1.0
 */
public class MyCasRealm extends CasRealm {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.getPrimaryPrincipal();

        
        User u=userService.findByUsername(username);
        
        
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        
        Set<String> permissionStrings= userService.findPermissions(username);
        Set<String> roleStrings= userService.getRolesAsString(u.getId().intValue());
        
        authorizationInfo.setRoles(roleStrings);
        authorizationInfo.setStringPermissions(permissionStrings);

        List<String> listUrl = new ArrayList<String>(permissionStrings);  
        List<String> listRole = new ArrayList<String>(roleStrings); 
//        for(int i = 0; i < listUrl.size(); i++){  
//            System.out.println("list1(" + i + ") --> " + listUrl.get(i));  
//        }  
       
//        StringBuffer sBuffer=new StringBuffer();
//        StringBuffer sBufferROLE=new StringBuffer();
        
//        for (String str : permissionStrings) {  
//            System.out.println(str); 
//            sBuffer.append(str+",");
//            
//        }  
//        for (String str : roleStrings) {  
//            System.out.println(str); 
//            sBufferROLE.append(str);
//            
//        } 
        
        Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute("userPermissionsList",listUrl);
		session.setAttribute("roleList", listRole);
        return authorizationInfo;
    }
}
